﻿using SymulatorEthernetWPF.SimObjects;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;

namespace SymulatorEthernetWPF.Shared
{
    public class HistoryElement
    {
        private readonly MemoryStream _memStream;

        public HistoryElement(byte[] data)
        {
            _memStream = new MemoryStream(data);
        }

        public HistoryElement()
        {
            var tmp = new List<ISerializable>();            
            StaticVars.MainWindow.undoButton.IsEnabled = true;
            foreach (UIElement it in StaticVars.MainWindow.customCanvas.Children)
            {
                try
                {
                    if(it is ISerializable)
                        tmp.Add((ISerializable) it);
                }
                catch
                {
                }
            }
            foreach (TaskQueueItem it in Simulation.taskQueue)
            {
                tmp.Add((ISerializable)it);
            }
            Serialize(tmp, out _memStream);
        }

        public List<ISerializable> Controls
        {
            get { return (List<ISerializable>) Deserialize(_memStream); }
        }

        public List<TaskQueueItem> TaskQueueItems
        {
            get 
            {
                List<ISerializable> tmp = (List<ISerializable>)Deserialize(_memStream);
                List<TaskQueueItem> tasks = new List<TaskQueueItem>();
                foreach (ISerializable it in tmp)
                {
                    if (it is TaskQueueItem)
                        tasks.Add((TaskQueueItem)it);
                }
                return tasks;
            }
        }

        private static void Serialize(object obj, out MemoryStream memStream)
        {
            memStream = new MemoryStream();
            var binaryFormatter = new BinaryFormatter(null,
                                                      new StreamingContext(StreamingContextStates.Clone));
            binaryFormatter.Serialize(memStream, obj);
            memStream.Seek(0, SeekOrigin.Begin);
        }

        private static object Deserialize(MemoryStream memStream)
        {
            var binaryFormatter = new BinaryFormatter(null,
                                                      new StreamingContext(StreamingContextStates.Clone));
            memStream.Seek(0, SeekOrigin.Begin);
            return binaryFormatter.Deserialize(memStream);
        }

        public MemoryStream GetMemoryStream()
        {
            return _memStream;
        }
    }
}